package com.atguigu.rabbitmq.three;

import com.atguigu.rabbitmq.util.RabbitmqUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.Scanner;

/**
 * @author codingBee
 * @since 2021/6/22/21:18
 * 测试消息在手动应答时是不丢失的，当信道由于异常断开连接时，会将未消费的消息重新放回队列。从而保证消息不丢失
 */
public class Task2 {
    //队列名称
    public static final String TASK_QUEUE_NAME = "ack_queue";

    public static void main(String[] args) throws IOException {
        //获取信道
        Channel chanel = RabbitmqUtil.getChannel();
        //声明队列,并且让队列持久化
        chanel.queueDeclare(TASK_QUEUE_NAME, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, null);
        //从控制台中接受信息
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String message = scanner.next();
            /**
             * Publish a message. 发送一个消息
             * Publishing to a non-existent exchange will result in a channel-level
             * protocol exception, which closes the channel.
             * Invocations of <code>Channel#basicPublish</code> will eventually block if a
             * <a href="https://www.rabbitmq.com/alarms.html">resource-driven alarm</a> is in effect.
             * @see com.rabbitmq.client.AMQP.Basic.Publish
             * @see <a href="https://www.rabbitmq.com/alarms.html">Resource-driven alarms</a>
             * @param exchange the exchange to publish the message to  要发送到的交换器
             * @param routingKey the routing key 路由 key
             * @param props other properties for the message - routing headers etc 其他信息的参数，如路由头
             * @param body the message body 消息体
             * @throws java.io.IOException if an error is encountered
             */
            //设置生产者发送消息为持久化消息（要求保存到磁盘上）保存到内存中
            chanel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes("UTF-8"));
            System.out.println("生产者发出消息：" + message);
        }
    }

}
